﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using Kristall.Engine;
using Kristall.Engine.Scripts;

namespace Kristall.MyGame.Scripts
{
    public class TriggerScript : Script
    {
        public string TargetId { get; set; }
        public string TargetScript { get; set; }
        public bool TriggerOnce { get; set; }
        public bool Toggle { get; set; }
        public bool TargetValue { get; set; }

        [XmlIgnore]
        private AABB target;

        bool triggered = false;

        public TriggerScript()
        {
            this.OnCollision += new EventHandler<CollisionEventArgs>(TriggerScript_OnCollision);
            TargetValue = true;
            TargetScript = "";
        }

        public override void Load(Level level, AABB aabb)
        {
            base.Load(level, aabb);

            this.target = level.FindEntityWithId(TargetId);
        }

        public void Trigger()
        {
            if (TriggerOnce && triggered)
                return;

            if (target == null)
                return;

            if (this.Enabled)
            {
                string[] scriptNames = TargetScript.Split(new []{','}, StringSplitOptions.RemoveEmptyEntries);

                target.Scripts.Where(delegate(Script script)
                {
                    if (scriptNames.Length > 0)
                        return scriptNames.Contains(script.Id);
                    else
                        return true;

                }).ToList().ForEach(delegate(Script script)
                {
                    if (Toggle)
                        script.Enabled = !script.Enabled;
                    else
                        script.Enabled = TargetValue;
                });

                triggered = true;
            }
        }

        void TriggerScript_OnCollision(object sender, CollisionEventArgs e)
        {
            Trigger();
        }

    }
}
